package com.dou361.jjdxm_ijkplayer;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.danikula.videocache.HttpProxyCacheServer;
import com.dou361.ijkplayer.bean.VideoijkBean;
import com.dou361.ijkplayer.listener.OnShowThumbnailListener;
import com.dou361.ijkplayer.listener.VideoClickListener;
import com.dou361.ijkplayer.widget.PlayStateParams;
import com.dou361.ijkplayer.widget.PlayerView;
import com.dou361.jjdxm_ijkplayer.utlis.MediaUtils;

import java.io.File;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

public class HPlayerActivity extends AppCompatActivity implements VideoClickListener{

    private PlayerView player;
    private Context mContext;
    private List<VideoijkBean> list;
    private PowerManager.WakeLock wakeLock;
    View rootView;

    ImageView iv_back;
    LinearLayout ll_left_select;
    View ll_video;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mContext = this;
        rootView = getLayoutInflater().from(this).inflate(R.layout.activity_h, null);
        setContentView(rootView);
        iv_back= (ImageView) findViewById(R.id.iv_back);
        ll_left_select= (LinearLayout) findViewById(R.id.ll_left_select);
        ll_video=findViewById(R.id.ll_video);



        /**虚拟按键的隐藏方法*/
//        rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//
//            @Override
//            public void onGlobalLayout() {
//
//                //比较Activity根布局与当前布局的大小
//                int heightDiff = rootView.getRootView().getHeight() - rootView.getHeight();
//                if (heightDiff > 100) {
//                    //大小超过100时，一般为显示虚拟键盘事件
//                    rootView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
//                } else {
//                    //大小小于100时，为不显示虚拟键盘或虚拟键盘隐藏
//                    rootView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
//
//                }
//            }
//        });

        /**常亮*/
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "liveTAG");
        wakeLock.acquire();
        list = new ArrayList<VideoijkBean>();
        //有部分视频加载有问题，这个视频是有声音显示不出图像的，没有解决http://fzkt-biz.oss-cn-hangzhou.aliyuncs.com/vedio/2f58be65f43946c588ce43ea08491515.mp4
        //这里模拟一个本地视频的播放，视频需要将testvideo文件夹的视频放到安卓设备的内置sd卡根目录中
        String url1 = getLocalVideoPath("my_video.mp4");
        if (!new File(url1).exists()) {
            url1 = "http://cdnbbbd.shoujiduoduo.com/bb/video/10000048/343696373.mp4";
//            Log.e("after","md5加密 "+generate(url1));
            HttpProxyCacheServer proxy = MyApplication.getProxy(this);
            url1  = proxy.getProxyUrl(url1);
        }
        String url2 = "http://cdnbbbd.shoujiduoduo.com/bb/video/10000048/343696373.mp4";
        HttpProxyCacheServer proxy2 = MyApplication.getProxy(this);
        url2  = proxy2.getProxyUrl(url2);
        VideoijkBean m1 = new VideoijkBean();
        m1.setStream("标清");
        m1.setUrl(url1);
        VideoijkBean m2 = new VideoijkBean();
        m2.setStream("高清");
        m2.setUrl(url2);
        list.add(m1);
        list.add(m2);
        player = new PlayerView(this, rootView) {
            @Override
            public PlayerView toggleProcessDurationOrientation() {
                hideSteam(getScreenOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                return setProcessDurationOrientation(getScreenOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ? PlayStateParams.PROCESS_PORTRAIT : PlayStateParams.PROCESS_LANDSCAPE);
            }

            @Override
            public PlayerView setPlaySource(List<VideoijkBean> list) {
                return super.setPlaySource(list);
            }
        }
                .setProcessDurationOrientation(PlayStateParams.PROCESS_PORTRAIT)
                .setScaleType(PlayStateParams.fillparent)
                .forbidTouch(false)
                .hideSteam(true)
                .hideCenterPlayer(true)
                .showThumbnail(new OnShowThumbnailListener() {
                    @Override
                    public void onShowThumbnail(ImageView ivThumbnail) {
                        Glide.with(mContext)
                                .load("http://pic2.nipic.com/20090413/406638_125424003_2.jpg")
                                .placeholder(R.color.cl_default)
                                .error(R.color.cl_error)
                                .into(ivThumbnail);
                    }
                })
                .setVideoClickListener(this)
                .setPlaySource(list)
                .setChargeTie(false,60)
                .startPlay();
    }


    /**
     * 播放本地视频
     */

    private String getLocalVideoPath(String name) {
        String sdCard = Environment.getExternalStorageDirectory().getPath();
        String uri = sdCard + File.separator + name;
        return uri;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (player != null) {
            player.onPause();
        }
        /**demo的内容，恢复系统其它媒体的状态*/
        MediaUtils.muteAudioFocus(mContext, true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (player != null) {
            player.onResume();
        }
        /**demo的内容，暂停系统其它媒体的状态*/
        MediaUtils.muteAudioFocus(mContext, false);
        /**demo的内容，激活设备常亮状态*/
        if (wakeLock != null) {
            wakeLock.acquire();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.onDestroy();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
//        if (player != null) {
//            player.onConfigurationChanged(newConfig);
//        }
    }

    @Override
    public void onBackPressed() {
//        if (player != null && player.onBackPressed()) {
//            return;
//        }
        super.onBackPressed();
        /**demo的内容，恢复设备亮度状态*/
        if (wakeLock != null) {
            wakeLock.release();
        }
    }

    @Override
    public void videoClick(boolean showBottom) {
        if (showBottom) {
            ObjectAnimator oaScaleX1=ObjectAnimator.ofFloat(ll_video,"scaleX",1f,0.7f);
            ObjectAnimator oaScaleY1=ObjectAnimator.ofFloat(ll_video,"scaleY",1f,0.7f);
            ObjectAnimator oaTranslate1=ObjectAnimator.ofFloat(ll_video,"translationY",0,-80);
            AnimatorSet animatorSet=new AnimatorSet();
            animatorSet.setDuration(200);
            animatorSet.playTogether(oaScaleX1,oaScaleY1,oaTranslate1);
            animatorSet.start();
        }else{
            ObjectAnimator oaScaleX2=ObjectAnimator.ofFloat(ll_video,"scaleX",0.7f,1f);
            ObjectAnimator oaScaleY2=ObjectAnimator.ofFloat(ll_video,"scaleY",0.7f,1f);
            ObjectAnimator oaTranslate2=ObjectAnimator.ofFloat(ll_video,"translationY",-80,0);
            AnimatorSet animatorSet2=new AnimatorSet();
            animatorSet2.setDuration(200);
            animatorSet2.playTogether(oaScaleX2,oaScaleY2,oaTranslate2);
            animatorSet2.start();
        }
    }

//    private static final String HASH_ALGORITHM = "MD5";
//    private static final int RADIX = 36;
//
//    public String generate(String imageUri) {
//        byte[] md5 = this.getMD5(imageUri.getBytes());
//        BigInteger bi = (new BigInteger(md5)).abs();
//        return bi.toString(36);
//    }
//
//    private byte[] getMD5(byte[] data) {
//        byte[] hash = null;
//
//        try {
//            MessageDigest digest = MessageDigest.getInstance("MD5");
//            digest.update(data);
//            hash = digest.digest();
//        } catch (NoSuchAlgorithmException var4) {
//        }
//
//        return hash;
//    }
}